var oldCatId;

function checkType() {
    var type = $(".type :selected").val();
    if(type == 'Простая регистрация') {
        $('#invitelist').hide();
        $('#reflink').show();
    } else {
        $('#invitelist').show();
        $('#reflink').hide();
    } 
}
///*****************************************************************************

function addInviteField() {
    var invateInputId = $("input.inviteInput").length-1;
    var newinvateInputId = invateInputId + 1;

    var inviteInput = '<input class="inviteInput input-xlarge" id="invites_['+newinvateInputId+']" type="text" name="Partner[invites][val]['+newinvateInputId+']" value="">';
    var checkBox = '<input class="invateCheckBox'+newinvateInputId+'" type="checkbox" name="Partner[invites][notWork]['+newinvateInputId+']">';
    var delBtn = '<img src="/images/admin/deletered.png" class="delButton" style="cursor:pointer" />';        

    $('#inviteWrap').append('<div id="inviteContainer'+newinvateInputId+'" class="form-inline" style="margin-bottom:10px;"><label class="text-info " for="invites_['+newinvateInputId+']">Инвайт:&nbsp;</label>' + inviteInput + '&nbsp;&nbsp;<label class="checkbox">' + checkBox + ' Не работает </label>&nbsp;&nbsp;' + delBtn + '</div>');
}
    
function addFields(catId, catName) {
    if($.inArray(catId, relCats) !== -1) return 0;
    relCats[catId] = catId;
    var relcatsInputId = $("input.relcats_input").length;
    var newrelcatsInputId = relcatsInputId + 1;
    var inputVal = '<input class="relcats_input input-xlarge" type="text" name="Partner[aboutRelCat][]" id="relcats_['+newrelcatsInputId+']" >';
    var inputRelCatId = '<input  type="hidden" name="Partner[relCat][]" value="'+ catId + '" />';
    var delBtn = '<img src="/images/admin/deletered.png" class="delInput" style="cursor:pointer" id="catId'+catId+'"/>';        
    $('.relParamList').append('<div><label class="text-info " for="relcats_['+newrelcatsInputId+']">Категория: <b>' + catName + '</b></label>' + '<span>Подсказка: </span>' + delBtn + inputVal + inputRelCatId +'&nbsp;</div>');
}

function addRelFields() {
    var inputVal = '<input class="relProfilesVal input-xlarge" type="text" name="Partner[relProfiles][]" value="" >';
    var inputTitleVal = '<input class=" input-xlarge" type="text" name="Partner[relProfilesTitle][]" value="" >';
    var delBtn = '<img src="/images/admin/deletered.png" class="delButton" style="cursor:pointer"/>'; 
    $('.listRelProfiles').append('<div><br/>Удалить:'+delBtn+'<br/><label class="text-info " for="">Урл связанного профиля:&nbsp;</label> ' + inputVal +'<label class="text-info " for="">Анкор</label>' + inputTitleVal+'</div>');
}

function addRatingTextField() {
    var inputTitle = '<input type="text" name="Partner[ratingTextField][]" value="" >';
    var aboutTextArea = '<textarea class="activeTextArea" name="Partner[aboutRatingTextField][]" placeholder="Описание" style="width:350px; height:20px"></textarea>';
    var delBtn = '<img src="/images/admin/deletered.png" class="delButton" style="cursor:pointer"/>'; 
    $('.ratingTextFieldsWrap').append('<br/><div>Удалить:'+delBtn+'<br/> Заголовок:<br/>'+inputTitle+'<br/>Описание:<br/>'+aboutTextArea+'</div>');
}

function checkCats() {
    var catid = $(".cats :selected").val();
    var partid = $("#partner_id").val();
    if(catid > 0) {
        $('#subcatsList').load('/ajax/getSubcats', 'catid='+catid+'&select='+catId);
        $('.listSortParams').load('/ajax/getSort', 'catid='+catid+'&partner_id='+partid);
    } else {
        $('#subcatsList').empty(); 
        $('.listSortParams').empty(); 
    }
}

function autoComlete(val, type) {
    if(val.length > 2) {
        $('#'+type+'Complit').load('ajax/getUsernames', 'login='+val, function() {
            $('#'+type+'Complit ul li a').click(function(){
                $('#'+type).val($(this).html());
                $('#'+type+'Complit').css({'display':'none'});
            });
        });
        $('#'+type+'Complit').css({'display':'block'});
    } else $('#'+type+'Complit').css({'display':'none'});
}

$(document).ready (function() {
    $('.type').change(function() {
        checkType();
    });

    $('.addInvite').click(function(){
        addInviteField();
    });
    
    $('.addRatingTextField').click(function(){
        addRatingTextField();
    });

    $("img.delInput").live("click", function(e){
        e.preventDefault();
        var catId = Number($(this).attr('id').replace(/\D+/g,""))
        relCats[catId] = undefined;
        $(this).parent().remove();
    });
    
    $('.delButton').live('click', function(){
        $(this).parent().remove();
    });
    
    $('.cats').change(function() {
        subCatsStack = new Array()
        oldCatId = 0;
        checkCats();
    });

    $('#relCats').change(function() {
        var catId = $("#relCats :selected").val();
        if(catId > 0) {
            var catName = $("#relCats :selected").html();
            addFields(catId, catName);
        } else $('#relParamList').empty();
    });

    $('#submitButton').click(function(){
        var relCatsStr = '';
        for(item in relCats) {
            if(relCatsStr) relCatsStr += ',';
            relCatsStr += item;
        }
        $('#relCat').attr({'value':relCatsStr});
        $('.stackData').attr('value', subCatsStack.toString());
        $('#partnerForm').submit();
    });

    $('.addRelProfiles').click(function(){
        addRelFields();
    });

    $('.delegate').keyup(function() {
        autoComlete($(this).val(), $(this).attr('id'));
    });

    $('.listSubCats').live('click', function(){
        console.log('d');
        if($(this).prop('checked')) subCatsStack.push($(this).val());
        else {
            for(var i=0; i<subCatsStack.length; i++) {
                if(subCatsStack[i] == $(this).val()) {subCatsStack.splice(i, 1);break;} 
            }
        }
        var catId = subCatsStack.length ? subCatsStack[0] : $(".cats :selected").val();
        if(catId != oldCatId) {
            oldCatId = catId;
            $('.listSortParams').load('/ajax/getSubCatsSort', 'catsid='+catId+'&partner_id='+$("#partner_id").val());
        }
    });
});       